package com.zhiqianbao.service;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.zhiqianbao.R;
import com.zhiqianbao.utils.Constants;
import com.zhiqianbao.utils.SdcardUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class UpdateService extends Service {

    private String apkURL;
    private int mProceess = -1;
    private SdcardUtils sdcardUtils;
    /* 下载中 */
    private static final int DOWNLOAD = 1;
    /* 下载结束 */
    private static final int DOWNLOAD_FINISH = 2;
    /* 记录进度条数量 */
    private int progress;
    /* 是否取消更新 */
    public static boolean cancelUpdate = false;
    /* 更新进度条 */
    public static  ProgressBar mProgress;
    public static  Dialog mDownloadDialog;
    public static String  force_update="false";

    private Handler mHandler = new Handler()
    {
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                // 正在下载
                case DOWNLOAD:
                    // 设置进度条位置
                    mProgress.setProgress(progress);
                    break;
                case DOWNLOAD_FINISH:
                    // 安装文件
                    installApk();
                    break;
                default:
                    break;
            }
        };
    };
    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onCreate() {
        sdcardUtils = new SdcardUtils();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent == null) {;
            stopSelf();//取消
        } else {
            apkURL = intent.getStringExtra("apkUrl");
            initFileDir();
            downloadApk();//启动下载
        }
        return super.onStartCommand(intent, flags, startId);
    }
    /**
     * 显示软件下载对话框
     */
    public static void showDownloadDialog(Context mContext,String forceUpdate)
    {
        force_update=forceUpdate;
        // 构造软件下载对话框
        AlertDialog.Builder builder = new Builder(mContext);
        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View view = inflater.inflate(R.layout.dialog_softupdate_progress, null);
        mProgress = (ProgressBar) view.findViewById(R.id.update_progress);
        builder.setView(view);
        if(!force_update.equals("true")) {
            // 取消更新
            builder.setNegativeButton("取消", new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    cancelUpdate = true;
                }
            });
        }
        mDownloadDialog = builder.create();
        mDownloadDialog.show();

        mDownloadDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if(force_update.equals("true")) {
                    if (keyCode == KeyEvent.KEYCODE_BACK) {
                        return true;
                    }
                }
                return false;
            }
        });
    }
    /**
     * 创建文件夹
     */
    private void initFileDir() {
        if (SdcardUtils.existSdcard()) {
            if (!sdcardUtils.isFileExist(Constants.FILE_DIR_NAME)) {//不存在就重新创建文件
                sdcardUtils.creatSDDir(Constants.FILE_DIR_NAME);
            }
        } else {
            Toast.makeText(getApplicationContext(),"sd卡不存在!",Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 下载apk文件
     */
    private void downloadApk()
    {
        // 启动新线程下载软件
        new downloadApkThread().start();
    }

    /**
     * 下载文件线程
     *
     * @author coolszy
     *@date 2012-4-26
     *@blog http://blog.92coding.com
     */
    private class downloadApkThread extends Thread
    {
        @Override
        public void run()
        {
            try
            {
                // 判断SD卡是否存在，并且是否具有读写权限
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
                {
                    // 获得存储卡的路径
                    File apkFile = new File(sdcardUtils.getSDPATH() + "/" + Constants.FILE_DIR_NAME + "/" + Constants.APP_NAME);
                    URL url = new URL(apkURL);
                    // 创建连接
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    // 获取文件大小
                    int length = conn.getContentLength();
                    // 创建输入流
                    InputStream is = conn.getInputStream();

                    FileOutputStream fos = new FileOutputStream(apkFile);
                    int count = 0;
                    // 缓存
                    byte buf[] = new byte[1024];
                    // 写入到文件中
                    do
                    {
                        int numread = is.read(buf);
                        count += numread;
                        // 计算进度条位置
                        progress = (int) (((float) count / length) * 100);
                        // 更新进度
                        mHandler.sendEmptyMessage(DOWNLOAD);
                        if (numread <= 0)
                        {
                            // 下载完成
                            mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                            break;
                        }
                        // 写入文件
                        fos.write(buf, 0, numread);
                    } while (!cancelUpdate);// 点击取消就停止下载.
                    fos.close();
                    is.close();
                }
            } catch (MalformedURLException e)
            {
                e.printStackTrace();
            } catch (IOException e)
            {
                e.printStackTrace();
            }
            // 取消下载对话框显示
            mDownloadDialog.dismiss();
        }
    };

    /**
     * 安装APK文件
     */
    private void installApk()
    {
        File apkFile = new File(sdcardUtils.getSDPATH() + "/" + Constants.FILE_DIR_NAME + "/" + Constants.APP_NAME);
        if (!apkFile.exists())
        {
            return;
        }
        // 通过Intent安装APK文件
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.setDataAndType(Uri.parse("file://" + apkFile.getAbsolutePath()), "application/vnd.android.package-archive");
        startActivity(i);
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }



}